package admin

import (
	"context"
	"strconv"
	"strings"

	"suci-go-zero/common/xerr"
	"suci-go-zero/internal/model"
	"suci-go-zero/internal/svc"
	"suci-go-zero/internal/types"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserListLogic {
	return &UserListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserListLogic) UserList(req *types.Page) (resp *types.AdminUserList, err error) {
	resp = &types.AdminUserList{
		AdminUsers: []types.AdminUser{},
		Page:       0,
		PageSize:   0,
		Total:      0,
	}
	logx.Info("---------1 数量查询------------------")
	//查询用户数量
	rb := l.svcCtx.Models.User.CountBuilder("id")
	total, err := l.svcCtx.Models.User.FindCount(l.ctx, rb)
	if err != nil {
		return nil, errors.Wrap(xerr.NewErrCode(xerr.DB_ERROR), "数量查询错误")
	}
	logx.Info("---------2  用户列表------------------")
	//查询用户信息
	rb = l.svcCtx.Models.User.RowBuilder()
	users, err := l.svcCtx.Models.User.FindPageListByPage(l.ctx, rb, int64(req.Page), int64(req.Size), "")
	if err != nil && err != model.ErrNotFound {
		return nil, errors.Wrap(xerr.NewErrCode(xerr.DB_ERROR), "数量查询错误")
	}
	logx.Info("---------2  角色列表------------------")
	//查询所有角色信息
	roles, err := l.svcCtx.Models.Role.FindAll(l.ctx, l.svcCtx.Models.Role.RowBuilder(), "")
	if err != nil && err != model.ErrNotFound {
		return nil, errors.Wrap(xerr.NewErrCode(xerr.DB_ERROR), "数量查询错误")
	}
	roleMap := map[int64]types.AdminRole{}
	for _, role := range roles {
		logx.Infof("%+v", role)
		roleMap[role.Id] = types.AdminRole{
			Id:         role.Id,
			Alias:      role.Alias,
			Label:      role.Label,
			Remark:     role.Remark,
			Status:     role.Status,
			Sort:       role.Sort,
			CreateTime: role.CreateTime.Format("2006-01-02 03:04:05"),
		}
	}
	logx.Info("---------2  拼装数据------------------")
	for _, user := range users {
		u := types.AdminUser{
			Id:         user.Id,
			Nickname:   user.Nickname,
			RealName:   user.RealName,
			Email:      user.Email,
			Name:       user.Name,
			Avatar:     user.Avatar,
			CreateTime: user.CreateTime.Format("2006-01-02 15:04:05"),
			Role:       []types.AdminRole{},
		}
		// logx.Info(user.Roles)

		for _, roleId := range strings.Split(user.Roles, ",") {
			id, _ := strconv.Atoi(roleId)
			// logx.Info(id)
			// logx.Infof("%+v", roleMap[int64(id)])
			if r, ok := roleMap[int64(id)]; ok {
				u.Role = append(u.Role, r)
			}
		}

		resp.AdminUsers = append(resp.AdminUsers, u)
	}
	resp.Total = int(total)
	resp.Page = req.Page
	resp.PageSize = req.Size

	return resp, nil
}
